<template>
  <div class="app-container">
    <form-header />
    <el-form ref="form" :model="form" :rules="rules" label-width="140px">
      <el-form-item label="商户logo">
        <el-upload
          action="#"
          list-type="picture-card"
          :on-remove="handleRemove"
          :on-change="handleChange"
          :auto-upload="false"
          :class="{ hide: hideUpload }"
          :file-list="imgsList"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>
      <el-form-item label="商户小图标">
        <el-upload
          action="#"
          list-type="picture-card"
          :on-remove="handleRemoveIcon"
          :on-change="handleChangeIcon"
          :auto-upload="false"
          :class="{ hide: hideUploadIcon }"
          :file-list="imgsListIcon"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>
      <el-form-item label="商户轮播图">
        <el-upload
          action="#"
          list-type="picture-card"
          :on-remove="handleRemoveSlide"
          :on-change="handleChangeSlide"
          :auto-upload="false"
          :file-list="imgsListSlide"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>
      <el-form-item label="机构名称" prop="name">
        <el-input v-model="form.name" clearable />
      </el-form-item>
      <el-form-item label="机构地址">
        <el-cascader
          v-model="selectedOptions"
          size="large"
          :options="areaOptions"
          style="width: 240px"
          @change="areaChange"
        />
      </el-form-item>
      <el-form-item label="详细地址" prop="detail">
        <el-input v-model="form.detail" clearable />
        <el-button
          type="text"
          @click="addressOptions.dialog = true"
        >位置调整</el-button>
      </el-form-item>
      <el-form-item label="商户负责人" prop="principalName">
        <el-input v-model="form.principalName" clearable />
      </el-form-item>
      <el-form-item label="商户负责人手机号" prop="serverPhone">
        <el-input v-model="form.serverPhone" clearable />
      </el-form-item>
      <el-form-item label="设施标签">
        <el-checkbox
          v-model="checkFacilityLabelAll"
          :indeterminate="isFacilityLabelIndeterminate"
          @change="handlecheckFacilityLabelAllChange"
        >全选</el-checkbox>
        <el-checkbox-group
          v-model="hasChoosebackstageFacilityLabels"
          @change="handleCheckedFacilityLabelsChange"
        >
          <el-checkbox
            v-for="item in backstageFacilityLabels"
            :key="item.id"
            :label="item.name"
          >{{ item.name }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="周围环境标签">
        <el-checkbox
          v-model="checkEnvironmentLabelAll"
          :indeterminate="isEnvironmentLabelIndeterminate"
          @change="handlecheckEnvironmentLabelAllChange"
        >全选</el-checkbox>
        <el-checkbox-group
          v-model="hasChoosebackstageEnvironmentLabels"
          @change="handleCheckedEnvironmentLabelsChange"
        >
          <el-checkbox
            v-for="item in backstageEnvironmentLabels"
            :key="item.id"
            :label="item.name"
          >{{ item.name }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="机构经营范围">
        <el-tabs
          v-model="topTypeIndex"
          style="position: relative; top: -2px"
          @tab-click="topTypeClick"
        >
          <el-tab-pane
            v-for="(item, index) in topTypeList"
            :key="item.id"
            :label="item.name"
            :name="index + ''"
          >
            <el-checkbox
              v-model="checkTypeAll"
              :indeterminate="isTypeIndeterminate"
              @change="handlecheckTypeAllChange"
            >全选</el-checkbox>
            <el-checkbox-group
              v-model="chooseTypes"
              @change="handleCheckedTypesChange"
            >
              <el-checkbox
                v-for="row in childrenType"
                :key="row.name"
                :label="row.name"
              >{{ row.name }}</el-checkbox>
            </el-checkbox-group>
          </el-tab-pane>
        </el-tabs>
      </el-form-item>
      <el-form-item label="机构详情">
        <tinymce v-model="form.synopsis" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      title="选择地址"
      :visible.sync="addressOptions.dialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      width="750px"
      @close="1"
    >
      <div ref="mapArry" style="width: 100%; height: 600px">
        <iframe
          id="mapPage"
          width="100%"
          height="100%"
          frameborder="0"
          src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=R6GBZ-ZPH6S-F6XOL-6OEWC-VZNX2-GKFMY&referer=myapp"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addressOptions.dialog = false">取 消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
import {
  merchantDetail,
  merchantUpdate,
  merchantType,
  getAllLabels,
  merchantAllType
} from '@/api/account'
import Tinymce from '@/components/Tinymce'
export default {
  name: 'MerchantEdit',
  components: { Tinymce },
  data() {
    return {
      rules: {
        name: [
          {
            required: true,
            trigger: 'blur',
            validator: this.g.checkInputIsEmpty
          }
        ],
        detail: [
          {
            required: true,
            trigger: 'blur',
            validator: this.g.checkInputIsEmpty
          }
        ],
        principalName: [
          {
            required: true,
            trigger: 'blur',
            validator: this.g.checkInputIsEmpty
          }
        ],
        serverPhone: [
          {
            required: true,
            trigger: 'blur',
            validator: this.g.checkInputIsEmpty
          },
          {
            pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
            message: '目前只支持中国大陆的手机号码'
          }
        ]
      },
      form: {
        id: '',
        name: '',
        logoImg: null,
        icon: null,
        lat: '',
        lng: '',
        addressIds: '',
        province: '',
        city: '',
        region: '',
        detail: '',
        principalName: '',
        serverPhone: '',
        categoryIds: [],
        categoryNames: [],
        categoryParentIds: [],
        categoryParentNames: [],
        synopsis: '',
        classify: '',
        labels: '',
        imgsFileLoop: []
      },
      imgsList: [],
      hideUpload: false,
      imgFile: null,

      imgsListIcon: [],
      hideUploadIcon: false,
      imgFileIcon: null,

      imgsListSlide: [],
      imgFileSlide: null,
      imgsFileLoop: [],

      areaOptions: regionData,
      selectedOptions: [],

      topTypeIndex: '0',
      allTypeList: [],
      topTypeList: [],
      childrenType: [],
      chooseTypes: [],
      checkTypeAll: false,
      isTypeIndeterminate: true,

      checkFacilityLabelAll: false,
      isFacilityLabelIndeterminate: false,
      backstageFacilityLabels: [],
      hasChoosebackstageFacilityLabels: [],

      checkEnvironmentLabelAll: false,
      isEnvironmentLabelIndeterminate: false,
      backstageEnvironmentLabels: [],
      hasChoosebackstageEnvironmentLabels: [],

      addressOptions: {
        dialog: false,
        address: '',
        lat: '',
        lng: ''
      }
    }
  },
  created() {
    this.form.id = this.$route.params['id']
    this.refresh()
    this.refreshAllType()
    this.refreshFacilityLabelList()
    this.refreshEnvironmentLabelList()
  },
  mounted() {
    const that = this
    // 为了防止火狐浏览器拖拽的时候以新标签打开
    document.body.ondrop = function(event) {
      event.preventDefault()
      event.stopPropagation()
    }
    window.addEventListener('message', function(event) {
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      var loc = event.data
      console.log(loc)
      if (loc && loc.module === 'locationPicker') {
        // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        // console.log('location', loc)
        that.form.lat = loc.latlng.lat
        that.form.lng = loc.latlng.lng
        that.form.detail = loc.poiaddress
      }
    },
    false
    )
  },
  methods: {
    refresh() {
      merchantDetail({ businessId: this.form.id }).then((response) => {
        const data = response.data
        if (data.logoImg !== null && data.logoImg !== '') {
          this.imgsList = [{ url: data.logoImg }]
          this.hideUpload = true
        }
        this.form.logoImg = data.logoImg

        if (data.icon !== null && data.icon !== '') {
          this.imgsListIcon = [{ url: data.icon }]
          this.hideUploadIcon = true
        }
        this.form.logoImgIcon = data.icon

        if (data.synopsisImg !== null && data.synopsisImg !== '') {
          this.form.synopsisImg = data.synopsisImg.split(',')
          this.form.synopsisImg.forEach(item => {
            this.imgsListSlide.push({
              url: item
            })
          })
        }
        // console.log(this.form.synopsisImg)
        this.form.name = data.name
        this.form.province = data.province
        this.form.city = data.city
        this.form.region = data.region
        this.form.addressIds = data.addressIds
        this.selectedOptions = []
        if (
          typeof TextToCode[data.province] !== 'undefined' &&
          typeof TextToCode[data.province][data.city] !== 'undefined' &&
          typeof TextToCode[data.province][data.city][data.region] !==
            'undefined'
        ) {
          this.selectedOptions.push(TextToCode[data.province].code + '')
          this.selectedOptions.push(
            TextToCode[data.province][data.city].code + ''
          )
          this.selectedOptions.push(
            TextToCode[data.province][data.city][data.region].code + ''
          )
        }

        this.form.detail = data.detail
        this.form.principalName = data.principalName
        this.form.serverPhone = data.serverPhone
        this.form.synopsis = data.synopsis

        if (data.backstageLabels !== null) {
          data.backstageLabels.map((item) => {
            if (item['type'] === 1) {
              this.hasChoosebackstageFacilityLabels.push(item['name'])
            }
            if (item['type'] === 2) {
              this.hasChoosebackstageEnvironmentLabels.push(item['name'])
            }
          })
        }

        this.chooseTypes =
          data.categoryNames === null ? [] : data.categoryNames.split(',')
        this.refreshTopType()
      })
    },
    handlecheckTypeAllChange(val) {
      if (val) {
        for (const item of this.childrenType) {
          this.chooseTypes.push(item['name'])
        }
        const setList = new Set(this.chooseTypes)
        this.chooseTypes = Array.from(setList)
      } else {
        for (const item of this.childrenType) {
          this.chooseTypes.splice(this.chooseTypes.indexOf(item), 1)
        }
      }
      this.isTypeIndeterminate = false
    },
    handleCheckedTypesChange(value) {
      const checkedCount = value.length
      this.checkTypeAll = checkedCount === this.childrenType.length
      this.isTypeIndeterminate =
        checkedCount > 0 && checkedCount < this.childrenType.length
    },
    areaChange(value) {
      const province = CodeToText[value[0]]
      const city = CodeToText[value[1]]
      const region = CodeToText[value[2]]
      this.form.province = province
      this.form.city = city
      this.form.region = region
      const addressIdsList = [value[0], value[1], value[2]]
      this.form.addressIds = addressIdsList.join(',')
    },
    refreshAllType() {
      merchantAllType().then((response) => {
        this.allTypeList = response.data
      })
    },
    refreshTopType() {
      merchantType({
        flagEnable: 1
      }).then((response) => {
        this.topTypeList = response.data
        this.refreshChildrenType(this.topTypeList[0]['id'])
      })
    },
    topTypeClick(tab, event) {
      console.log(tab, event)
      this.topTypeIndex = tab.name
      this.refreshChildrenType(
        this.topTypeList[parseInt(this.topTypeIndex)]['id']
      )
    },
    refreshChildrenType(parentId) {
      merchantType({
        parentId: parentId,
        flagEnable: 1
      }).then((response) => {
        this.childrenType = response.data
        let count = 0
        for (const item of this.childrenType) {
          for (const row of this.chooseTypes) {
            if (item['name'] === row) {
              count++
            }
          }
        }
        this.checkTypeAll = count === this.childrenType.length
        this.isTypeIndeterminate =
          count > 0 && count < this.childrenType.length
      })
    },
    async submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.goToSubmit()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    async goToSubmit() {
      if (this.imgFile === null && this.form.logoImg === null) {
        this.$message({ message: '请选择图片', type: 'error' })
        return
      }

      if (this.imgFile !== null) {
        await this.uploadImgToOss(this.imgFile).then((response) => {
          console.log('图片上传结果：' + JSON.stringify(response))
          this.form.logoImg = response
        })
      }

      if (this.imgFileIcon !== null) {
        await this.uploadImgToOss(this.imgFileIcon).then((response) => {
          console.log('图片上传结果：' + JSON.stringify(response))
          this.form.icon = response
        })
      }
      if (this.imgFileSlide !== null) {
        await this.handleLoopImgsSlide().then(res => {
          if (res !== '500') {
            this.form.synopsisImg.push(...res)
          }
        })
      }

      const categoryIds = []
      let categoryParentIds = []
      let categoryParentNames = []

      let hasClassify1 = false
      let hasClassify2 = false
      this.allTypeList.forEach((parentItem) => {
        for (const item of parentItem['categories']) {
          for (const row of this.chooseTypes) {
            if (item['name'] === row && item['classify'] === 1) {
              hasClassify1 = true
            }
            if (item['name'] === row && item['classify'] === 2) {
              hasClassify2 = true
            }
            if (row === item['name']) {
              categoryIds.push(item['id'])
              categoryParentIds.push(parentItem['id'])
              categoryParentNames.push(parentItem['name'])
            }
          }
        }
      })

      const setCategoryParentIds = new Set(categoryParentIds)
      categoryParentIds = Array.from(setCategoryParentIds)

      const setCategoryParentNames = new Set(categoryParentNames)
      categoryParentNames = Array.from(setCategoryParentNames)

      this.form.classify = hasClassify1 && hasClassify2 ? 3 : hasClassify1 ? 1 : hasClassify2 ? 2 : null
      this.form.categoryIds = categoryIds.length > 0 ? categoryIds.join(',') : ''
      this.form.categoryNames = this.chooseTypes.length > 0 ? this.chooseTypes.join(',') : ''
      this.form.categoryParentIds = categoryParentIds.length > 0 ? categoryParentIds.join(',') : ''
      this.form.categoryParentNames = categoryParentNames.length > 0 ? categoryParentNames.join(',') : ''

      const labelIds = []
      for (const item of this.backstageFacilityLabels) {
        for (const row of this.hasChoosebackstageFacilityLabels) {
          if (item['name'] === row) {
            labelIds.push(item['id'])
          }
        }
      }
      for (const item of this.backstageEnvironmentLabels) {
        for (const row of this.hasChoosebackstageEnvironmentLabels) {
          if (item['name'] === row) {
            labelIds.push(item['id'])
          }
        }
      }
      this.form.labels = labelIds.join(',')
      this.form.synopsisImg = this.form.synopsisImg ? this.form.synopsisImg.join(',') : ''

      merchantUpdate(this.form).then((response) => {
        console.log(response)
        this.$message({ message: '提交成功', type: 'success' })
        this.$router.push({ name: 'MerchantList' })
      })
    },
    handleLoopImgsSlide() {
      return new Promise((resolve, reject) => {
        const imgArr = []
        const index = this.imgsFileLoop.length
        if (index !== 0) {
          this.imgsFileLoop.forEach((item, i) => {
            this.uploadImgToOss(item).then(response => {
              imgArr.push(response)
              if (index === i + 1) {
                resolve(imgArr)
              }
            })
          })
        } else {
          resolve('500')
        }
      })
    },
    handleRemove(file, fileList) {
      this.hideUpload = false
    },
    handleChange(file, fileList) {
      this.imgFile = fileList.length > 0 ? file : null
      this.hideUpload = fileList.length >= 1
    },
    handleRemoveIcon(file, fileList) {
      this.hideUploadIcon = false
    },
    handleChangeIcon(file, fileList) {
      this.imgFileIcon = fileList.length > 0 ? file : null
      this.hideUploadIcon = fileList.length >= 1
    },
    handleRemoveSlide(file, fileList) {
      console.log(file)
      console.log(fileList)
      console.log(this.imgsFileLoop)
      const arr = []
      fileList.forEach((item, index) => {
        if (item.status === 'success') {
          arr.push(item.url)
        }
      })
      this.imgsFileLoop.forEach((item, index) => {
        if (item.name === file.name) {
          this.imgsFileLoop.splice(index, 1)
        }
      })
      this.form.synopsisImg = [...new Set(arr)]
    },
    handleChangeSlide(file, fileList) {
      this.imgFileSlide = fileList.length > 0 ? file : null
      this.imgsFileLoop.push(this.imgFileSlide)
    },
    refreshFacilityLabelList() {
      getAllLabels({
        status: 1,
        type: 1
      }).then((response) => {
        this.backstageFacilityLabels = response['data']

        const checkedCount = this.hasChoosebackstageFacilityLabels.length
        this.checkFacilityLabelAll =
          checkedCount === this.backstageFacilityLabels.length
        this.isFacilityLabelIndeterminate =
          checkedCount > 0 &&
          checkedCount < this.backstageFacilityLabels.length
      })
    },
    handlecheckFacilityLabelAllChange(val) {
      if (val) {
        this.hasChoosebackstageFacilityLabels = []
        this.backstageFacilityLabels.map((item) => {
          this.hasChoosebackstageFacilityLabels.push(item['name'])
        })
      } else {
        this.hasChoosebackstageFacilityLabels = []
      }

      this.isFacilityLabelIndeterminate = false
    },
    handleCheckedFacilityLabelsChange(value) {
      const checkedCount = value.length
      this.checkFacilityLabelAll =
        checkedCount === this.backstageFacilityLabels.length
      this.isFacilityLabelIndeterminate =
        checkedCount > 0 && checkedCount < this.backstageFacilityLabels.length
    },
    refreshEnvironmentLabelList() {
      getAllLabels({
        status: 1,
        type: 2
      }).then((response) => {
        this.backstageEnvironmentLabels = response['data']

        const checkedCount = this.hasChoosebackstageEnvironmentLabels.length
        this.checkEnvironmentLabelAll =
          checkedCount === this.backstageEnvironmentLabels.length
        this.isEnvironmentLabelIndeterminate =
          checkedCount > 0 &&
          checkedCount < this.backstageEnvironmentLabels.length
      })
    },
    handlecheckEnvironmentLabelAllChange(val) {
      if (val) {
        this.hasChoosebackstageEnvironmentLabels = []
        this.backstageEnvironmentLabels.map((item) => {
          this.hasChoosebackstageEnvironmentLabels.push(item['name'])
        })
      } else {
        this.hasChoosebackstageEnvironmentLabels = []
      }

      this.isEnvironmentLabelIndeterminate = false
    },
    handleCheckedEnvironmentLabelsChange(value) {
      const checkedCount = value.length
      this.checkEnvironmentLabelAll =
        checkedCount === this.backstageEnvironmentLabels.length
      this.isEnvironmentLabelIndeterminate =
        checkedCount > 0 &&
        checkedCount < this.backstageEnvironmentLabels.length
    }
  }
}
</script>

<style lang="scss" scoped>
.hide /deep/.el-upload--picture-card {
  display: none;
}
</style>
